package com.luli.Utils;

import com.luli.entity.Content;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 陆离
 * 2022/5/3 19:31:07
 * 解析网页工具类
 */
@Slf4j
public class HtmlParseUtils {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    public  List<Content> parseID(String keywords) throws IOException {
        //获取请求 https://search.jd.com/Search?keyword=
        //前提需要链接网络 不能获取ajax数据
        String url = "https://search.jd.com/Search?keyword=" + keywords;
        //解析网页返回的就是js页面  document对象
        Document document = Jsoup.parse(new URL(url), 3000);
        //所有在js中使用的方法都能用了
        Element element = document.getElementById("J_goodsList");
        //获取所有li元素
        Elements li = element.getElementsByTag("li");

        List<Content> contentList = new ArrayList<>();
        //获取元素中的内容 每一个li标签
        for (Element el : li) {
            //关于图片很多的网址，所有的图片都是延迟加载的
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            String words = el.getElementsByClass("promo-words").eq(0).text();
            String currShop = el.getElementsByClass("curr-shop").eq(0).text(); //店铺名
            String icons = el.getElementsByClass("goods-icons").eq(0).text(); //是否自营
            //String id = el.attr("data-sku");  //京东爬取的id
            //自己生成的id 雪花算法集成
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            content.setWords(words);
            content.setCurrShop(currShop);
            content.setIcons(icons);
            content.setId(String.valueOf(UUID.randomUUID()));
            contentList.add(content);
        }

        //获取搜索框下得提示
        Element elementById = document.getElementById("navitems-2014");
        Element elementById1 = elementById.getElementById("navitems-group1");
        Elements li1 = elementById1.getElementsByTag("li");
        Map<String, Object> map = new HashMap<>();
        for (Element element1 : li1) {
            Content content = new Content();
            String searchDown = element1.getElementsByClass("b").text();
            content.setSearchDown(searchDown);
            contentList.add(content);
        }

        log.info("contentList",contentList);
        return contentList;
    }

    /**
     * 获取搜索框下的信息
     * @param keywords
     * @return
     * @throws IOException
     */
    public  static List<Map<String,Object>> getSearchDown(String keywords) throws IOException {
        //获取请求 https://search.jd.com/Search?keyword=
        //前提需要链接网络 不能获取ajax数据
        String url = "https://search.jd.com/Search?keyword=" + keywords;
        //解析网页返回的就是js页面  document对象
        Document document = Jsoup.parse(new URL(url), 3000);
        List<Map<String,Object>> contentList = new ArrayList<>();
        //获取搜索框下得提示
        Element elementById = document.getElementById("navitems-2014");
        Element elementById1 = elementById.getElementById("navitems-group1");
        Elements li1 = elementById1.getElementsByTag("li");
        Map<String, Object> map = new HashMap<>();
        for (Element element1 : li1) {
            String searchDown = element1.getElementsByClass("b").text();
            map.put("searchDown",searchDown);
            contentList.add(map);
        }
        return contentList;
    }


    /**
     * 获取数据，实现搜索功能
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    public  List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
        if (pageNo <= 1) {
            pageNo = 1;
        }
        //条件搜素
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准匹配关键字
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }




}
